package com.example.rabbit;

import com.example.common.JsonUtil;
import com.example.common.MessageHelper;
import com.example.config.RabbitConfig;
import com.example.entity.email.Mail;
import com.example.utils.SendMailUtil;


import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
@Slf4j
public class ConsumerMailService {

    private static final Logger LOGGER = LoggerFactory.getLogger(ConsumerMailService.class);

    @Autowired
    private SendMailService sendMailService;



    /**
     * 监听消息队列，手动确认模式，必须手动调用ack或者nack方法
     * 配置参数：spring.rabbitmq.listener.simple.acknowledge-mode=manual
     * @param message
     * @param channel
     * @throws IOException
     */
//    @RabbitListener(queues = {"mail.queue"})
//    public void consumeFromAck(Message message, Channel channel) throws IOException {
//        LOGGER.info("收到消息：{}", message.toString());
//        //将消息转化为对象
//        Mail mail = MessageHelper.msgToObj(message, Mail.class);
//
//        // 手动确认模式
//        long tag = message.getMessageProperties().getDeliveryTag();
//        boolean success = sendMailService.send(mail);
//        if (success) {
//            // 消费成功，消息会被删除
//            channel.basicAck(tag, false);
//        } else {
//            // 消费失败，重新返回队列
//            channel.basicNack(tag, false, true);
//        }
//    }

    /**
     * 监听消息队列，自动确认模式，无需调用ack或者nack方法，当程序执行时才删除消息
     * 配置参数：spring.rabbitmq.listener.simple.acknowledge-mode=auto
     * @param message
     */
    @RabbitListener(queues = {"mail.queue"})
    public void consumeFromAuto(Message message) {
        LOGGER.info("收到消息：{}", message.toString());
        // 获取消息ID
        Mail mail = MessageHelper.msgToObj(message, Mail.class);
      log.info("mail:{}",mail);
        // 发送邮件
       sendMailService.send(mail);

    }
}
